package Servlet;

import com.cyy.dao.userDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/register")
public class registerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("开始注册...");
        request.setCharacterEncoding("UTF-8");
        String name=request.getParameter("name");
        String pwd=request.getParameter("pwd");
        String doublePwd=request.getParameter("doublePwd");
        String email=request.getParameter("email");
        String message;
//        得到当前日期
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String dateTime = df.format(date);
        userDao userDao = new userDao();
//        正式注册，操作数据库
        boolean success= false;
        try {
//            判断是否能够成功插入数据库（有唯一键限制）
            success = userDao.addUser(name,pwd,email,dateTime);
        } catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }
        if(!success)
        {
            message="用户名已经存在！请重新输入！";
        }
        else
        {
            if(!doublePwd.equals(pwd))
            {
                message="两次输入密码不相同！请重新输入！";
            }
            else
            {
                message="注册成功！";
                System.out.println(message);
                request.setAttribute("message", message);
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }
        System.out.println(message);
        request.setAttribute("message", message);
        request.getRequestDispatcher("/register.jsp").forward(request, response);
        }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
